<?php
class BaseModel
{
    const RISK_LIMIT = 20;
    public static $db;

    public $fields = array();
    public $arrParams = array();

    public function __construct()
    {
        if ($this->table)
        {
            $strSql = 'DESC ' . $this->table;
            $arrRows = $this->db()->query($strSql);
            foreach ($arrRows as $item)
            {
                $this->fields[] = $item['Field'];
            }
        }
    }

    public function db()
    {
        if(!isset(self::$db))
        {
            $config = Yii::app()->params['dbconf'];//Config :: $mysqlConfig;
            $balance = mt_rand(1,count($config['machine']));
            $handle = ConnectionMan::getMysqli($selServer, $config['machine'],$config['auth'],
                $config['talk']['connect_timeout_ms'],$config['talk']['strategy'], $balance);
            if($handle != false)
            {
                self::$db = new DB(false,$handle);
                self::$db->query('set names utf8');
                // 去掉对批量操作的安全检查
                //self::$db->addHook(DB::HK_AFTER_QUERY,1,array('BaseModel','riskCheck'));
                self::$db->autoCommit(false);
                register_shutdown_function(array(self::$db,'commit'));
            }
            else{
                //logging
                Yii::log('connect db failed','error');
            }
        }
        
        return self::$db;
    }

    public static function riskCheck($db,&$ret,$args)
    {
        $sql = $db->getLastSQL();
        $str = trim($sql);
        $str = strtolower($str);

        $flag = 0;
        if(strpos($str,'update') === 0)
            $flag = 1;
        if(strpos($str,'delete') === 0)
            $flag = 2;
        if($flag > 0)
        {
            if($flag === 1)
            {
                $info = $db->getLastQueryInfo();
                preg_match("/rows matched:\s+(\d+)/i",$info,$matches);
                $numRows = $matches[1];
            }
            else
                $numRows = $db->affectedRows;

            if($numRows >= self::RISK_LIMIT)
            {
                Yii::log("high risk sql:".$sql,'error');
                $db->rollback();
                $ret = false;
            }
        }
    }

    public function setParams($arrParams)
    {
        $this->arrParams = $arrParams;
    }

    /**
    * @brief    获取记录数，主要用于分页
    */
    public function getCount()
    {
        $intCount = 0;
        $strSql = 'SELECT COUNT(*) AS total FROM `' . $this->table . '` WHERE 1 = 1';

        //存在is_del字段
        if (in_array('is_del', $this->fields))
        {
            if (intval($this->arrParams['condition']['is_del']) === 1)
            {
            }
            else
            {
                $strSql.= ' AND `is_del` = 0';
            }
        }

        if (!empty($this->arrParams['condition']))
        {
            foreach ($this->arrParams['condition'] as $key => $value)
            {
                if ($key === 'is_del')
                {
                    continue;
                }
                if (intval($value) > 0)
                {
                    $strSql.= ' AND `' . $key . '` = "' . $value . '"';
                }
                else
                {
                    $strSql.= ' AND `' . $key . '` LIKE "%' . $value . '%"';
                }
            }
        }
		
		if (!empty($this->arrParams['where']))
		{
			$strSql .= " AND (".$this->arrParams['where'].")";
		}

        $arrRows = $this->db()->query($strSql);
        return $arrRows[0]['total'];
    }

    /*
    * @brief    获取数据列表
    */
    public function getList()
    {
        $strFields = isset($this->arrParams['fields']) ? $this->arrParams['fields'] : '*';
        $strSql = 'SELECT ' . $strFields . ' FROM `' . $this->table . '` WHERE 1 = 1';

        $strOrderBy = '';
        //存在is_del字段
        if (in_array('is_del', $this->fields))
        {
            if (intval($this->arrParams['condition']['is_del']) === 1)
            {
            }
            else
            {
                $strSql.= ' AND `is_del` = 0';
            }

            $strOrderBy = ' ORDER BY `is_del` ASC';
        }
        
        if (!empty($this->arrParams['condition']))
        {
            foreach ($this->arrParams['condition'] as $key => $value)
            {
                if ($key === 'is_del')
                {
                    continue;
                }

                if (intval($value) > 0 || $value == '0')
                {
                    $strSql.= ' AND `' . $key . '` = "' . $value . '"';
                }
                else
                {
                    $strSql.= ' AND `' . $key . '` LIKE "%' . $value . '%"';
                }
            }

        }

        if (!empty($this->arrParams['where']))
        {
            $strSql .= " AND (".$this->arrParams['where'].")";
        }
        if (!empty($this->arrParams['orderby']))
        {
            $arrOrderBy = array();
            foreach ($this->arrParams['orderby'] as $key => $value)
            {
                $arrOrderBy[] = '`' . $key . '` ' . $value;
            }
            if (!empty($strOrderBy))
            {
                $strOrderBy.= ',' . implode(',', $arrOrderBy);
            }
            else
            {
                $strOrderBy = ' ORDER BY ' . implode(',', $arrOrderBy);
            }
        }
        $strSql.= $strOrderBy;
        if (isset($this->arrParams['offset']) && isset($this->arrParams['limit']))
        {
            $strSql.= ' LIMIT ' . intval($this->arrParams['offset']) . ',' . intval($this->arrParams['limit']);
        }
        if (($arrResult = $this->db()->query($strSql)) !== false)
        {
            return $arrResult;
        }
        else
        {
            return array();
        }
    }

    /*
    * @brief    获取单条记录信息
    */
    public function getItem()
    {
        $strFields = isset($this->arrParams['fields']) ? $this->arrParams['fields'] : '*';
        $strSql = 'SELECT ' . $strFields . ' FROM `' . $this->table . '` WHERE 1 = 1';
        if (!empty($this->arrParams))
        {
            foreach ($this->arrParams as $key => $value)
            {
                $strSql.= ' AND `' . $key . '` = "' . $value . '"';
            }
        }
        $strSql.= ' LIMIT 1';
        $arrRows = $this->db()->query($strSql);
        if (!empty($arrRows))
        {
            return $arrRows[0];
        }
        else
        {
            return array();
        }
    }

    //保存信息
    public function save($arrData)
    {
        $arrValues = array();
        if (intval($arrData['id']) > 0)
        {
            foreach ($arrData as $key => $value)
            {
                if (in_array($key, $this->fields))
                {
                    $arrValues[] = '`' . $key . '` = "' . $this->db()->escapeString($value) . '"';
                }
            }
            $strSql = 'UPDATE `' . $this->table . '` SET ' . implode(',', $arrValues) . ' WHERE id = ' . intval($arrData['id']);
        }
        else
        {
            unset($arrData['id']);
            $arrFields = array();
            foreach ($arrData as $key => $value)
            {
                if (in_array($key, $this->fields))
                {
                    $arrFields[] = '`' . $key . '`';
                    $arrValues[] = '"' . $this->db()->escapeString($value) . '"';
                }
            }
            $strSql = 'INSERT INTO `' . $this->table . '` (' . implode(',', $arrFields) . ') VALUES (' . implode(',', $arrValues) . ')';
        }
	Yii::log("base build sql:".$strSql,'info');
        $mixResult = $this->db()->query($strSql);
        if ($mixResult !== false)
        {
            if (intval($arrData['id']) === 0)
            {
                return $this->db()->getInsertID();
            }
            else
            {
                return intval($arrData['id']);
            }
        }
        else
        {
            return false;
        }
    }


}
